// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';
import * as fs from 'fs';
import * as path from 'path';
import * as XLSX from 'xlsx';
import * as myItem from './item';
import { table } from 'console';
// This method is called when your extension is activated
// Your extension is activated the very first time the command is executed
interface ModelConFig {
    data: string[][];
    fileName: string;
}
interface FileNode {
    name: string;
    path: string;
    model?: string;
    // configName?: string[];
    type: 'folder' | 'model';
    children?: FileNode[];
}// 判断一行是否为空
function isRowEmpty(row: (string | null | undefined)[]): boolean {
    return row.every(cell => !cell || cell.trim() === "");
}

// 判断某一列是否为空
function isColumnEmpty(data: string[][], colIndex: number): boolean {
    return data.every(row => !row[colIndex] || row[colIndex]?.trim() === "");
}

// 删除二维数组中倒数所有的空行和空列
function removeLastEmptyRowsAndColumns(data: string[][]): string[][] {
    // 删除空行
    for (let i = data.length - 1; i >= 0; i--) {
        if (isRowEmpty(data[i])) {
            data.splice(i, 1); // 删除空行
        } else {
            break; // 如果遇到非空行，停止删除
        }
    }

    if (data.length === 0) {
        return data; // 如果所有行都被删除，直接返回空数组
    }

    const colCount = data[0].length;

    // 删除空列（从最后一列开始向前遍历）
    for (let j = colCount - 1; j >= 0; j--) {
        if (isColumnEmpty(data, j)) {
            data.forEach(row => row.splice(j, 1)); // 删除该列
        } else {
            break; // 如果遇到非空列，停止删除
        }
    }

    return data;
}
async function readModelConfig(itemPath: string) {
    let data: string[][] = [];
    if (!itemPath || !itemPath.endsWith('.xlsx')) {
        return data;
    }

    const uri = vscode.Uri.file(itemPath);
    try {
        const fileData = await vscode.workspace.fs.readFile(uri);
        const workbook = XLSX.read(fileData, { type: 'buffer' });
        const worksheet = workbook.Sheets[workbook.SheetNames[0]];

        const range = worksheet['!ref'];
        if (range) {
            const [startCell, endCell] = range.split(':');
            const startRow = parseInt(startCell.match(/\d+/)![0]);
            const endRow = parseInt(endCell.match(/\d+/)![0]);
            const startCol = startCell.match(/[A-Z]+/)![0];
            const endCol = endCell.match(/[A-Z]+/)![0];
            const startColIndex = startCol.charCodeAt(0) - 'A'.charCodeAt(0);
            const endColIndex = endCol.charCodeAt(0) - 'A'.charCodeAt(0);

            for (let row = startRow; row <= endRow; row++) {
                const rowData: string[] = [];
                for (let col = startColIndex; col <= endColIndex; col++) {
                    const cell = worksheet[`${String.fromCharCode('A'.charCodeAt(0) + col)}${row}`];
                    rowData.push(cell ? cell.v : '');
                }
                data.push(rowData);
            }
        }
    } catch (error) {
        console.error('Error reading Excel file:', error);
    }
    
    return removeLastEmptyRowsAndColumns(data);
}
async function saveModelConfig(itemPath: string, config: string[][]) {
    if (!itemPath || !itemPath.endsWith('.xlsx')) {
        return;
    }

    const uri = vscode.Uri.file(itemPath);
    try {
        const workbook = XLSX.utils.book_new();
        // 创建新的工作表并覆盖之前的内容
        const worksheet = XLSX.utils.aoa_to_sheet(config);
        XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1', true); // true 表示替换

        const xlsxData = XLSX.write(workbook, { bookType: 'xlsx', type: 'buffer' });
        await vscode.workspace.fs.writeFile(uri, Buffer.from(xlsxData));
    } catch (error) {
        console.error('Error saving Excel file:', error);
    }
}
async function saveEmptyXlsxFile(itemPath: string) {
    if (!itemPath || !itemPath.endsWith('.xlsx')) {
        return;
    }

    const uri = vscode.Uri.file(itemPath);
    try {
        // 创建新的工作簿
        const workbook = XLSX.utils.book_new();

        // 创建空的工作表
        const emptySheet = XLSX.utils.aoa_to_sheet([[]]); // 空数组表示创建空的表
        XLSX.utils.book_append_sheet(workbook, emptySheet, 'Sheet1');

        // 写入文件
        const xlsxData = XLSX.write(workbook, { bookType: 'xlsx', type: 'buffer' });
        await vscode.workspace.fs.writeFile(uri, Buffer.from(xlsxData));
    } catch (error) {
        console.error('Error saving Excel file:', error);
    }
}
async function deleteFile(filePath: string): Promise<number> {
    if (!filePath) {
        return 0; // 文件路径无效时返回 0
    }

    const uri = vscode.Uri.file(filePath);
    try {
        await vscode.workspace.fs.delete(uri, { recursive: false, useTrash: true });
        return 1; // 删除成功时返回 1
    } catch (error) {
        console.error('Error deleting file:', error);
        vscode.window.showErrorMessage(`Error deleting file: ${filePath}`);
        return 0; // 删除失败时返回 0
    }
}
async function saveModelStr(modelPath: string, str: string) {
    if (!modelPath || !modelPath.endsWith('.xml')) {
        return;
    }

    const uri = vscode.Uri.file(modelPath);

    try {
        // 将字符串编码为 Uint8Array
        const encoder = new TextEncoder();
        const data = encoder.encode(str);

        // 写入文件
        await vscode.workspace.fs.writeFile(uri, data);

        vscode.window.showInformationMessage('文件保存成功！');
    } catch (error) {
        console.error('写入文件时出错:', error);
        vscode.window.showErrorMessage(`保存文件失败：${error}`);
    }
}
async function createFolder(folderPath: string):Promise<boolean> {
    
    const uri = vscode.Uri.file(folderPath);
    try {
        await vscode.workspace.fs.createDirectory(uri);
        vscode.window.showInformationMessage(`文件夹创建成功: ${uri.fsPath}`);
        return true;
    } catch (error) {
        vscode.window.showErrorMessage(`文件夹创建失败: ${error}`);
        return false;
    }
}
async function createEmptyFile(fileName: string):Promise<boolean> {
  
    const emptyContent = new Uint8Array(); // 空文件内容
    const uri = vscode.Uri.file(fileName);
    try {
      await vscode.workspace.fs.writeFile(uri, emptyContent);
      vscode.window.showInformationMessage(`文件 '${fileName}' 创建成功`);
      return true;
    } catch (error) {
      vscode.window.showErrorMessage("创建文件失败：" + error);
      return false;
    }
  }

// 读取文件夹下所有的.xlsx文件
function readAllModelConfig(dirPath: string) {
    // const items = fs.readdirSync(dirPath);
    // const allData: FileNode = {
    //     name: '',
    //     path: '',
    //     type: 'folder',
    //     config: []
    // };
    // let index: number = 0;
    // items.forEach(item => {
    //     if (allData.config) {
    //         allData.config[index].fileName = item.replace(/\.[^/.]+$/, "");
    //         // 如果文件类型为xlsx，则读取文件内容
    //         allData.config[index].data = readModelConfig(dirPath + "/" + item);
    //     }
    // });
    // return allData; // 返回所有读取到的数据
}
function readModelConfigList(dirPath: string) {
    // 读取文件内容
    const items = fs.readdirSync(dirPath);
    let allData: string[] = [];
    items.forEach(item => {
        const filePath = item.replace(/\.[^/.]+$/, "");;
        if (filePath !== 'model' && !filePath.startsWith('~$')) {
            allData.push(filePath);
        }
    });
    return allData;
}
function readDirectory(dirPath: string): FileNode[] {
    const items = fs.readdirSync(dirPath);
    const result: FileNode[] = [];

    items.forEach(item => {
        const itemPath = path.join(dirPath, item);
        const stats = fs.statSync(itemPath);

        if (stats.isDirectory()) {
            if (itemPath.endsWith('-item')) {
                // 如果是文件
                result.push({
                    name: item,
                    path: itemPath,
                    type: 'model',
                    // configName: readModelConfigList(itemPath)
                });
            } else {
                // 如果是文件夹，递归读取子文件夹
                result.push({
                    name: item,
                    path: itemPath,
                    type: 'folder',
                    children: readDirectory(itemPath)
                });
            }
        }
    });

    return result;
}
async function getModelData(dirPath: string) {
    if (!dirPath) {
        return '';
    }
    const modelPath = path.join(dirPath, 'model.xml');

    const uri = vscode.Uri.file(modelPath);
    try {
        const fileData = await vscode.workspace.fs.readFile(uri);
        // 使用 TextDecoder 将 Uint8Array 转换为字符串
        const content = new TextDecoder('utf-8').decode(fileData);
        return content;
    } catch (error) {
        console.error('Error reading Excel file:', error);
        return '';
    }
}
async function createFolderOrItem(fpath: string, type: string)
{
    let ret = false;
    if (type === 'createFolder'){
        ret = await createFolder(fpath);
    } else {
        ret = await createFolder(fpath);
        ret = ret && await createEmptyFile(path.join(fpath, 'model.xml'));
    }
    return ret;
}
function getWebviewContent(): string {
    return `<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Template Manager with SortableJS</title>
    <style>
        body {
            font-family: sans-serif;
        }

        #controls {
            margin-bottom: 10px;
        }

        #controls button {
            margin-right: 5px;
            padding: 8px 16px;
            background-color: #007acc;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }

        #controls button:hover {
            background-color: #005a9e;
        }

        /* 根列表不设置左侧填充 */
        .template-list {
            list-style-type: none;
            padding-left: 0;
        }

        /* 嵌套列表保持缩进 */
        .nested-list {
            list-style-type: none;
            padding-left: 20px;
        }

        .template-item {
            margin: 5px 0;
            position: relative;
        }

        /* 文件夹 (Folder) 样式 */
        .folder-content {
            padding: 10px 5px;
            display: flex;
            /* 图标和名称水平排列 */
            flex-direction: row;
            /* 横向排列 */
            align-items: center;
            /* 垂直居中 */
            cursor: pointer;
            position: relative;
        }

        .folder-icon {
            display: inline-block;
            width: 16px;
            height: 16px;
            margin-right: 5px;
            /* 增加图标和名称之间的间距 */
            background-size: contain;
            background-repeat: no-repeat;
        }

        .folder-name {
            font-size: 14px;
            color: #e6e6e6;
        }

        .folder-content:hover {
            background-color: #2c2c2c;
        }

        .item-content {
            padding: 2px 5px;
            display: flex;
            flex-direction: column;
            /* 名称和描述垂直排列 */
            position: relative;
        }

        /* 名称的样式 */
        .item-name {
            font-size: 14px;
            color: #e6e6e6;
            margin-bottom: 2px;
        }

        /* 描述的样式，超出部分显示省略号 */
        .item-description {
            font-size: 10px;
            color: #bbbbbb;
            white-space: nowrap;
            /* 单行显示 */
            overflow: hidden;
            text-overflow: ellipsis;
            /* 超出部分显示省略号 */
        }

        /* 贯穿整个页面的横线样式 */
        .hr-line {
            position: absolute;
            left: 0;
            right: 0;
            width: 500vw;
            /* 使用视口宽度确保横线贯穿页面 */
            transform: translateX(-50vw);
            /* 横线从页面左侧贯穿到右侧 */
            border: none;
            border-top: 1px solid #2c2c2c;
            margin: 0;
            z-index: -1;
            /* 保证横线位于内容的后面 */
            bottom: -1px;
            /* 放在 item-content 的下方 */
        }

        /* 描述鼠标悬停时显示完整内容 */
        .item-description:hover {
            white-space: normal;
            overflow: visible;
        }

        /* 展开/收起的按钮样式 */
        .toggle-btn {
            background-color: transparent;
            border: none;
            color: #007acc;
            cursor: pointer;
            font-size: 12px;
            padding: 5px 0;
        }

        .item-content:hover {
            background-color: #2c2c2c;
        }

        .folder-item>.item-content {
            cursor: pointer;
        }

        /* 文件夹图标样式 */
        .folder-item .folder-icon {
            display: inline-block;
            width: 16px;
            height: 16px;
            margin-right: 5px;
            background-size: contain;
            background-repeat: no-repeat;
        }

        /* 关闭状态的文件夹图标 */
        .folder-item .folder-icon.closed {
            background-image: url("data:image/svg+xml,%3Csvg t='1726498307916' class='icon' viewBox='0 0 1024 1024' version='1.1' xmlns='http://www.w3.org/2000/svg' p-id='15004' width='200' height='200'%3E%3Cpath d='M938.656 942.944h-896c-25.6 0-42.656-17.056-42.656-42.656v-768c0-25.6 17.056-42.656 42.656-42.656h554.656c12.8 0 21.344 4.256 29.856 12.8l157.856 157.856h153.6c25.6 0 42.656 17.056 42.656 42.656v597.344c0 21.344-17.056 42.656-42.656 42.656zM85.344 857.6H896v-512H85.344v512z m0-597.344H665.6l-85.344-85.344H85.312v85.344z' p-id='15005' fill='%23e6e6e6'%3E%3C/path%3E%3C/svg%3E");
        }

        /* 打开状态的文件夹图标 */
        .folder-item .folder-icon.open {
            background-image: url("data:image/svg+xml,%3Csvg t='1726498195118' class='icon' viewBox='0 0 1260 1024' version='1.1' xmlns='http://www.w3.org/2000/svg' p-id='13883' width='200' height='200'%3E%3Cpath d='M1058.848012 935.688021H88.993243l113.018307-453.124559h969.854769zM88.993243 88.839223h397.403905l52.566655 157.699962h554.052534v147.186632h-893.63312A88.837646 88.837646 0 0 0 115.802237 461.011134l-27.33466 109.338641zM1181.853983 394.251483V246.013518A88.311979 88.311979 0 0 0 1093.016337 157.701539h-490.972549l-31.014326-95.67131A88.311979 88.311979 0 0 0 486.922815 0.001577H88.993243A88.311979 88.311979 0 0 0 0.155598 88.839223V935.688021a88.837646 88.837646 0 0 0 0 10.513331v14.718663a87.260646 87.260646 0 0 0 26.808993 37.847991h5.782332a87.260646 87.260646 0 0 0 39.950657 14.718663h986.150432A88.837646 88.837646 0 0 0 1145.057325 946.201352l113.018307-453.124559a88.837646 88.837646 0 0 0-76.221649-98.82531z' fill='%23e6e6e6' p-id='13884'%3E%3C/path%3E%3C/svg%3E");
        }

        .add-btn {
            margin-left: auto;
            background-color: transparent;
            color: #666;
            border: none;
            cursor: pointer;
            font-size: 16px;
        }

        .add-btn:hover {
            color: #000;
        }
        #item-context-menu {
            display: none;
            position: absolute;
            background-color: #2e2e2e;
            color: white;
            border: 1px solid #444;
            box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.5);
            z-index: 1000;
            border-radius: 8px;
        }
        #item-context-menu ul {
            list-style: none;
            margin: 0;
            padding: 10px;
        }
        #item-context-menu li {
            padding: 5px;
            cursor: pointer;
        }
        #item-context-menu li:hover {
            background-color: #444;
        }
        #folder-context-menu {
            display: none;
            position: absolute;
            background-color: #2e2e2e;
            color: white;
            border: 1px solid #444;
            box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.5);
            z-index: 1000;
            border-radius: 8px;
        }
        #folder-context-menu ul {
            list-style: none;
            margin: 0;
            padding: 10px;
        }
        #folder-context-menu li {
            padding: 5px;
            cursor: pointer;
        }
        #folder-context-menu li:hover {
            background-color: #444;
        }
    </style>
    <!-- 引入 SortableJS -->
    <script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>
</head>

<body>
    <div id="controls">
        <button onclick="showInputDialog('folder')">Add Folder</button>
        <button onclick="showInputDialog('item')">Add Item</button>
    </div>
    <ul id="template-list" class="template-list">
        <!-- 文件夹和项将添加在这里 -->
    </ul>
    <!-- 文件项的右键菜单 -->
    <div id="item-context-menu"
        style="display: none; position: absolute; background-color: #2e2e2e; color: white; border: 1px solid #444; box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.5); z-index: 1000; border-radius: 8px;">
        <ul style="list-style: none; margin: 0; padding: 10px;">
            <li id="item-context-delete" style="padding: 5px; cursor: pointer;">删除项</li>
            <li id="item-context-rename" style="padding: 5px; cursor: pointer;">重命名项</li>
        </ul>
    </div>

    <!-- 文件夹的右键菜单 -->
    <div id="folder-context-menu"
        style="display: none; position: absolute; background-color: #2e2e2e; color: white; border: 1px solid #444; box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.5); z-index: 1000; border-radius: 8px;">
        <ul style="list-style: none; margin: 0; padding: 10px;">
            <li id="folder-context-delete" style="padding: 5px; cursor: pointer;">删除文件夹</li>
            <li id="folder-context-rename" style="padding: 5px; cursor: pointer;">重命名文件夹</li>
            <li id="folder-context-add-item" style="padding: 5px; cursor: pointer;">添加项</li>
        </ul>
    </div>
    <script>
        const vscode = acquireVsCodeApi(); // 获取 VSCode API，用于与 TS 端通信
        let currentTarget = null;
        // 保存当前操作类型和父元素引用
        let currentAction = null;
        let currentParent = null;
        let uniqueIdCounter = 0;

        function generateUniqueId() {
            return 'id-' + uniqueIdCounter++;
        }
        // 初始化根列表的 Sortable 实例
        const rootList = document.getElementById('template-list');
        initSortable(rootList);
        const itemContextMenu = document.getElementById('item-context-menu');
        const folderContextMenu = document.getElementById('folder-context-menu');
        // 点击页面其他地方隐藏自定义菜单
        document.addEventListener('click', () => {
            itemContextMenu.style.display = 'none';
            folderContextMenu.style.display = 'none';
        });
        document.getElementById('item-context-delete').addEventListener('click', async () => {
            if (currentTarget) {
                itemContextMenu.style.display = 'none';
            }
            // 找到要删除的模板项（li元素）
            const itemElement = currentTarget.closest('.template-item');
    
            if (itemElement) {
                // 从父节点中移除该模板项
                itemElement.parentNode.removeChild(itemElement);
            }
        });
        document.getElementById('item-context-rename').addEventListener('click', async () => {
            if (currentTarget) {
                itemContextMenu.style.display = 'none';
                const itemElement = currentTarget.closest('.template-item');
                const itemId = itemElement.dataset.id;
                const currentName = itemElement.querySelector('.item-name').textContent;
        
                // 发送重命名请求到 TS 端，包含旧名称
                vscode.postMessage({
                    command: 'renameItem',
                    itemId: itemId,
                    oldName: currentName
                });
            }
        });
        document.getElementById('folder-context-delete').addEventListener('click', async () => {
            if (currentTarget) {
                folderContextMenu.style.display = 'none';
            }
            // 找到要删除的文件夹元素（li.folder-item）
            const folderElement = currentTarget.closest('.folder-item');
    
            if (folderElement) {
                // 从父节点中移除该文件夹及其子元素
                folderElement.parentNode.removeChild(folderElement);
            }
        });
        document.getElementById('folder-context-rename').addEventListener('click', async () => {
            if (currentTarget) {
                folderContextMenu.style.display = 'none';
                const folderElement = currentTarget.closest('.folder-item');
                const folderId = folderElement.dataset.id;
                const currentName = folderElement.querySelector('.folder-name').textContent;
        
                // 发送重命名请求到 TS 端，包含旧名称
                vscode.postMessage({
                    command: 'renameFolder',
                    folderId: folderId,
                    oldName: currentName
                });
            }
        });
        document.getElementById('folder-context-add-item').addEventListener('click', async () => {
            if (currentTarget) {
                folderContextMenu.style.display = 'none';
            }
        });
        // 显示输入对话框
        function showInputDialog(action) {
            vscode.postMessage({
                command: 'showInputBox', // 自定义消息类型
                type: action, // 区分是添加文件夹还是项目
            });
        }
        function updateItemName(itemId, newName) {
            // 根据 itemId 找到对应的模板项
            const itemElement = document.querySelector(\`.template-item[data-id='\${itemId}']\`);
            if (itemElement) {
                const itemNameElement = itemElement.querySelector('.item-name');
                if (itemNameElement) {
                    itemNameElement.textContent = newName;
                }
            }
        }
        function updateFolderName(folderId, newName) {
            // 根据 folderId 找到对应的文件夹
            const folderElement = document.querySelector(\`.folder-item[data-id='\${folderId}']\`);
            if (folderElement) {
                const folderNameElement = folderElement.querySelector('.folder-name');
                if (folderNameElement) {
                    folderNameElement.textContent = newName;
                }
            }
        }
        
        window.addEventListener('message', (event) => {
            const message = event.data;
            console.log(message);
            switch (message.command) {
                case 'updateItemName':
                    updateItemName(message.itemId, message.newName);
                    break;
                case 'updateFolderName':
                    updateFolderName(message.folderId, message.newName);
                    break;
                case 'createFolder':
                    // 在 WebView 中创建文件夹
                    if (message.status) {
                        const folder = createFolder(message.name, generateUniqueId());
                        document.getElementById('template-list').appendChild(folder);
                        initSortable(folder.querySelector('.nested-list'));
                    }
                    break;
                case 'createItem':
                    // 在 WebView 中创建项目
                    if (message.status) {
                        const item = createItem(message.name, generateUniqueId(), message.path);
                        document.getElementById('template-list').appendChild(item);
                    }
                    break;
                case 'loadFileStructure':
                    console.log('loadFileStructure');
                    const fileStructure = message.data;
                    console.log(fileStructure);
                    // 调用函数生成文件和文件夹的界面
                    renderFileStructure(fileStructure, document.getElementById('template-list'));
                    break;
                // ...其他消息处理
            }
        });
        function renderFileStructure(fileNodes, container) {
            fileNodes.forEach(node => {
                const nodeId = generateUniqueId(); // 使用已有的生成唯一ID的函数
        
                if (node.type === 'folder') {
                    // 创建文件夹元素
                    const folderElement = createFolder(node.name, nodeId);
        
                    // 如果有子节点，递归创建
                    if (node.children && node.children.length > 0) {
                        const nestedList = folderElement.querySelector('.nested-list');
                        renderFileStructure(node.children, nestedList);
                    }
        
                    container.appendChild(folderElement);
                } else if (node.type === 'model') {
                    // 创建模板项元素
                    const itemElement = createItem(node.name, nodeId, node.path);
                    container.appendChild(itemElement);
                }
            });
        }
        
        // 创建文件夹项
        function createFolder(name, id) {
            const folderItem = document.createElement('li');
            folderItem.classList.add('folder-item');
            folderItem.dataset.id = id;

            const itemContent = document.createElement('div');
            itemContent.classList.add('folder-content');

            // 创建文件夹图标
            const folderIcon = document.createElement('span');
            folderIcon.classList.add('folder-icon', 'closed'); // 初始为关闭状态
            itemContent.appendChild(folderIcon);

            // 添加文件夹名称
            const folderName = document.createElement('span');
            folderName.textContent = name;
            folderName.classList.add('folder-name');
            itemContent.appendChild(folderName);

            // 用于存放子项的嵌套列表
            const nestedList = document.createElement('ul');
            nestedList.classList.add('nested-list');
            nestedList.style.display = 'none';

            // 添加展开/收起功能
            itemContent.addEventListener('click', (event) => {
                const isHidden = nestedList.style.display === 'none';
                nestedList.style.display = isHidden ? 'block' : 'none';
                // 切换图标类名
                folderIcon.classList.toggle('open', isHidden);
                folderIcon.classList.toggle('closed', !isHidden);
            });
            // 添加右键菜单功能
            itemContent.addEventListener('contextmenu', (e) => {
                e.preventDefault();
                currentTarget = e.target;
                folderContextMenu.style.display = 'block';
                folderContextMenu.style.top = \`\${e.clientY}px\`;
                folderContextMenu.style.left = \`\${e.clientX}px\`;
            });

            folderItem.appendChild(itemContent);
            folderItem.appendChild(nestedList);

            return folderItem;
        }

        // 创建模板项
        function createItem(name, id, path) {
            const templateItem = document.createElement('li');
            templateItem.classList.add('template-item');
            templateItem.dataset.id = id;

            // 为模板项设置唯一的 data-id
            templateItem.dataset.id = generateUniqueId();
            const itemContent = document.createElement('div');
            itemContent.classList.add('item-content');

            // 添加项名称
            const itemName = document.createElement('span');
            itemName.textContent = name.slice(0, -5);
            itemName.classList.add('item-name');
            itemContent.appendChild(itemName);
            description = 'Description';
            // 描述部分
            const itemDescription = document.createElement('span');
            itemDescription.textContent = description;
            itemDescription.classList.add('item-description');
            itemContent.appendChild(itemDescription);

            // 添加贯穿式的横线
            const hrLine = document.createElement('hr');
            hrLine.classList.add('hr-line');
            itemContent.appendChild(hrLine);

            // 点击事件，打开 Editor 页面
            itemContent.addEventListener('click', () => {
                vscode.postMessage({
                    command: 'openEditor',
                    itemName: name,
                    itemPath: path,
                    description: description
                });
            });
            // 添加右键菜单功能
            itemContent.addEventListener('contextmenu', (e) => {
                e.preventDefault();
                currentTarget = e.target;
                itemContextMenu.style.display = 'block';
                itemContextMenu.style.top = \`\${e.clientY}px\`;
                itemContextMenu.style.left = \`\${e.clientX}px\`;
            });
            // 将 itemContent 添加到 li 中
            templateItem.appendChild(itemContent);

            return templateItem;
        }

        // 初始化嵌套列表的 Sortable 实例
        function initSortable(listElement) {
            new Sortable(listElement, {
                group: {
                    name: 'nested',
                    pull: true,
                    put: true
                },
                animation: 150,
                fallbackOnBody: true,
                swapThreshold: 0.65,
                handle: '.item-content, .folder-content',
                onEnd: function (evt) {
                    // 拖拽结束后的回调，可以在这里更新数据结构
                },
                onMove: function (evt, originalEvent) {
                    const target = evt.to;
                    // 如果拖拽到的是文件夹的 nested-list，上级是 folder-item
                    if (target && target.classList.contains('nested-list') && target.parentElement.classList.contains('folder-item')) {
                        target.style.display = 'block'; // 确保嵌套列表可见

                        // 切换图标为打开状态
                        const folderIcon = target.parentElement.querySelector('.folder-icon');
                        folderIcon.classList.add('open');
                        folderIcon.classList.remove('closed');
                    }
                }
            });
        }
        window.addEventListener('DOMContentLoaded', () => {
            vscode.postMessage({ command: 'ready' });
        });
    </script>
</body>

</html>`;
}
function getEditorContent(context: vscode.ExtensionContext, webview: vscode.Webview) {
    return `<!DOCTYPE html>
<html lang="en">

<head>
    <!-- 引入 Prism.js 的暗色主题 CSS（Okaidia） -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-okaidia.min.css" rel="stylesheet" />
    <!-- 引入 Prism.js 的核心 JS 文件 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/prism.min.js"></script>

    <meta charset="UTF-8">
    <!-- 内容安全策略 -->
    <meta http-equiv="Content-Security-Policy"
        content="default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline';">
    <style>
        body {
            margin: 0;
            padding: 0;
            display: flex;
            height: 100vh;
        }

        .container {
            display: flex;
            width: 100%;
            height: 100%;
            background-color: #f5f2f0;
        }

        .left-pane {
            background-color: #f5f2f0;
            color: white;
            overflow: auto;
            height: 100vh; /* 使left-pane占满视口高度 */
            display: flex;
            width: 50%;
            flex-direction: column; /* 子元素垂直排列 */
        }
        .left-pane h3 {
            flex: 0 0 auto; /* 内容决定高度，不拉伸 */
            margin: 0;
            padding: 10px; /* 根据需要调整内边距 */
            /* height: 50px; */
        }

        .left-pane pre {
            flex: 1 1 auto; /* 占据剩余空间，可拉伸 */
            margin: 0;
            overflow: auto; /* 内容超出时添加滚动条 */
            background-color: #1f1f1f;

        }
        .left-pane code[contenteditable="true"]:focus {
            outline: none; /* 移除默认的聚焦边框 */
        }

        /* 解决在编辑状态下，用户无法选择或输入内容的问题 */
        .left-pane code {
            word-break: break-all;
        }
        .right-pane {
            display: flex;
            flex-direction: column;
            overflow: hidden;
            width: 50%;
        }

        .top {
            padding: 10px;
            background-color: #007acc;
            color: white;
            overflow: auto;
            height: 50%;
        }

        .bottom {
            padding: 10px;
            background-color: #ffffff;
            overflow: auto;
            height: 50%;
        }

        .divider-horizontal {
            height: 5px;
            background-color: #666;
            cursor: row-resize;
        }

        .divider-vertical {
            width: 5px;
            background-color: #666;
            cursor: col-resize;
        }

        #xlsx-table td {
            padding: 5px;
            border: 1px solid #ccc;
        }

        .file-item {
            cursor: pointer;
        }

        #file-operate-menu {
            display: none;
            position: absolute;
            background-color: #2e2e2e;
            color: white;
            border: 1px solid #444;
            box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.5);
            z-index: 1000;
            border-radius: 8px;
        }

        #file-operate-menu ul {
            list-style: none;
            margin: 0;
            padding: 10px;
        }

        #file-operate-menu li {
            padding: 5px;
            cursor: pointer;
        }

        #file-operate-menu li:hover {
            background-color: #444;
        }
        #right-pane-menu {
            display: none;
            position: absolute;
            background-color: #2e2e2e;
            color: white;
            border: 1px solid #444;
            box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.5);
            z-index: 1000;
            border-radius: 8px;
        }

        #right-pane-menu ul {
            list-style: none;
            margin: 0;
            padding: 10px;
        }

        #right-pane-menu li {
            padding: 5px;
            cursor: pointer;
        }

        #right-pane-menu li:hover {
            background-color: #444;
        }
    </style>
</head>

<body>
    <div class="container">
        <!-- 左侧面板 -->
        <div class="left-pane">
            <button id="model-or-output">切换输出</button>
            <button id="save-model">保存模板</button>
            <pre><code id="code-block" class="language-xml" contenteditable="true"></code></pre>
    </div>

    <!-- 垂直分割线 -->
    <div class="divider-vertical" id="vertical-divider"></div>

    <!-- 右侧面板 -->
    <div class="right-pane">
        <div class="top" id="top-pane">
            <h3>文件目录</h3>
            <ul id="file-list">
            </ul>
        </div>

        <!-- 水平分割线 -->
        <div class="divider-horizontal" id="horizontal-divider"></div>

        <div class="bottom" id="bottom-container">
            <div id="xlsx-display">
                <h4>XLSX 内容显示与编辑</h4>
                <button id="save-button">保存</button>
                <table id="xlsx-table" border="1" style="width: 100%; text-align: left;"></table>
            </div>
        </div>
    </div>
    </div>

    <div id="file-operate-menu"
        style="display: none; position: absolute; background-color: #2e2e2e; color: white; border: 1px solid #444; box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.5); z-index: 1000; border-radius: 8px;">
        <ul style="list-style: none; margin: 0; padding: 10px;">
            <li id="context-delete">删除</li>
            <li id="context-rename">重命名</li>
        </ul>
    </div>
    <div id="right-pane-menu"
        style="display: none; position: absolute; background-color: #2e2e2e; color: white; border: 1px solid #444; box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.5); z-index: 1000; border-radius: 8px;">
        <ul style="list-style: none; margin: 0; padding: 10px;">
            <li id="context-new-config">新建配置</li>
        </ul>
    </div>

    <script>
        const vscode = acquireVsCodeApi();
        const verticalDivider = document.getElementById('vertical-divider');
        const leftPane = document.querySelector('.left-pane');
        const rightPane = document.querySelector('.right-pane');

        const horizontalDivider = document.getElementById('horizontal-divider');
        const topPane = document.getElementById('top-pane');
        const bottomPane = document.getElementById('bottom-container');

        const fileList = document.getElementById('file-list');
        const fileOperateMenu = document.getElementById('file-operate-menu');
        const rightPaneMenu = document.getElementById('right-pane-menu');
        const table = document.getElementById('xlsx-table');
        const saveButton = document.getElementById('save-button');
        
        const codeElement = document.getElementById('code-block');
        const changeButton = document.getElementById('model-or-output');
        const saveModel = document.getElementById('save-model');

        let showType = 'model';
        let currentConfigName = '';

        let modelStr = '';
        let outputStr = '';
        let currentTarget = null;
        let currentPath = '';
        // left top bottom
        let currentFocus = 'left'

        let isDraggingVertical = false;
        let isDraggingHorizontal = false;

        saveButton.addEventListener('click', () => {
            saveConfigToXlsx();
        }
        );
        // 垂直分割线拖动事件
        verticalDivider.addEventListener('mousedown', (e) => {
            isDraggingVertical = true;
            document.addEventListener('mousemove', onVerticalDrag);
            document.addEventListener('mouseup', stopDragging);
        });

        // 水平分割线拖动事件
        horizontalDivider.addEventListener('mousedown', (e) => {
            isDraggingHorizontal = true;
            document.addEventListener('mousemove', onHorizontalDrag);
            document.addEventListener('mouseup', stopDragging);
        });

        // 修改 code 内容的函数
        function updateCodeContent(newContent) {
            // 设置新内容，自动转义 HTML 特殊字符
            codeElement.textContent = newContent;
            Prism.highlightElement(codeElement);
        }
        function onVerticalDrag(e) {
            if (!isDraggingVertical) return;
            const containerRect = document.querySelector('.container').getBoundingClientRect();
            const leftWidth = ((e.clientX - containerRect.left) / containerRect.width) * 100;
            leftPane.style.width = \`\${leftWidth}%\`;
            rightPane.style.width = \`\${100 - leftWidth}%\`;
        }

        function onHorizontalDrag(e) {
            if (!isDraggingHorizontal) return;
            const rightPaneHeight = rightPane.getBoundingClientRect().height;
            const topHeight = ((e.clientY - rightPane.getBoundingClientRect().top) / rightPaneHeight) * 100;
            topPane.style.height = \`\${topHeight}%\`;
            bottomPane.style.height = \`\${100 - topHeight}%\`;
        }

        function stopDragging() {
            isDraggingVertical = false;
            isDraggingHorizontal = false;
            document.removeEventListener('mousemove', onVerticalDrag);
            document.removeEventListener('mousemove', onHorizontalDrag);
            document.removeEventListener('mouseup', stopDragging);
        }
        function formatStrings(template, dataArray) {
            if (!template || !Array.isArray(dataArray) || dataArray.length < 2) {
                return '';
            }

            const paramNames = dataArray[0]; // 获取参数名列表
            let output = '';
            
            // 遍历参数值行
            for (let i = 1; i < dataArray.length; i++) {
                const row = dataArray[i];
                let formattedString = template;

                // 遍历参数名并进行替换
                for (let j = 0; j < paramNames.length; j++) {
                const paramName = paramNames[j];
                const paramValue = row[j];

                // 创建正则表达式，匹配占位符 \${参数名}
                const regex = new RegExp(\`\\\\\$\\\\{\${paramName}\\\\}\`, \'g\');

                // 替换占位符为对应的参数值
                formattedString = formattedString.replace(regex, paramValue);
                }

                // 将替换后的字符串添加到输出字符串
                output += formattedString;
            }

            return output;
        }
        function getModelStr() {
            let ret = codeElement.textContent;
            const textarea = document.createElement('textarea');
            textarea.innerHTML = ret;
            return textarea.value;
        }
        function saveModelFunc() {
            vscode.postMessage({
                command: 'saveModel',
                modelStr: modelStr,
                configPath: currentPath,
                configName: currentConfigName
            });
        }
        // 新增一个空行
        function addEmptyRow() {
            const row = table.insertRow();
            const colCount = table.rows[0].cells.length;

            for (let i = 0; i < colCount; i++) {
                const newCell = row.insertCell();
                newCell.contentEditable = true; // 设置单元格为可编辑
            }
        }

        // 新增一个空列
        function addEmptyColumn() {
            Array.from(table.rows).forEach(row => {
                const newCell = row.insertCell();
                newCell.contentEditable = true; // 设置单元格为可编辑
            });
        }
        // 添加初始的空行和空列
        function addEmptyRowAndColumn(table) {
            const row = table.insertRow();
            const cell = row.insertCell();
            cell.contentEditable = true; // 设置单元格为可编辑
        }
        // 确保表格的最后一行和最后一列是空的
        function ensureLastRowAndColumnAreEmpty() {
          if (table.rows.length === 0 || table.rows[0].cells.length === 0) {
            // 如果表格没有任何行或列，直接添加一行一列
            addEmptyRowAndColumn(table);
            return;
          }
    
          const lastRowIndex = table.rows.length - 1;
          const lastColIndex = table.rows[0].cells.length - 1;
        
        console.log(lastRowIndex);
        console.log(lastColIndex);
          // 检查最后一行是否为空
          if (!isRowEmpty(table.rows[lastRowIndex])) {
            addEmptyRow();
          }
        
          // 检查最后一列是否为空
          if (!isColumnEmpty(table, lastColIndex)) {
            addEmptyColumn();
          }
        }
        // 删除倒数所有不为空的行和列
        function removeLastNonEmptyRowsAndColumns() {
        
        if (table.rows.length === 0 || table.rows[0].cells.length === 0) {
            return; // 如果表格没有行或列，直接返回
        }

        const rowCount = table.rows.length;
        const colCount = table.rows[0].cells.length;

        // 1. 删除倒数不为空的行
        for (let i = rowCount - 1; i >= 0; i--) {
            const row = table.rows[i];
            if (isRowEmpty(row)) {
            table.deleteRow(i); // 删除为空的行
            } else {
            break; // 如果遇到空行，停止删除
            }
        }

        // 2. 删除倒数为空的列
        for (let j = colCount - 1; j >= 0; j--) {
            if (isColumnEmpty(table, j)) {
            // 删除每一行中的这一列
            Array.from(table.rows).forEach(row => {
                row.deleteCell(j);
            });
            } else {
            break; // 如果遇到空列，停止删除
            }
        }
        }

        function operateFocus() {
            if (currentFocus !== 'bottom') {
                console.log('removeLastRowAndColumn');
                removeLastNonEmptyRowsAndColumns();
            } else {
                console.log('ensureLastRowAndColumnAreEmpty');
                ensureLastRowAndColumnAreEmpty(); 
            }
        }
        leftPane.addEventListener('click', () => {
            currentFocus = 'left';
            operateFocus();
        });
        topPane.addEventListener('click', () => {
            currentFocus = 'top';
            operateFocus();
        });
        bottomPane.addEventListener('click', () => {
            currentFocus = 'bottom';
            operateFocus();
        });
        // 文件名右键事件，显示自定义右键菜单
        fileList.addEventListener('contextmenu', (e) => {
            e.preventDefault();
            currentConfigName = e.target.innerText;
            if (e.target.classList.contains('file-item')) {
                rightPaneMenu.style.display = 'none';
                currentTarget = e.target;
                fileOperateMenu.style.display = 'block';
                fileOperateMenu.style.top = \`\${e.clientY}px\`;
                fileOperateMenu.style.left = \`\${e.clientX}px\`;
            }
        });
        // 文件名左键击事件
        fileList.addEventListener('click', function (e) {
            // 向ts侧发送文件名
            currentConfigName = e.target.innerText;
            if (e.target.classList.contains('file-item')) {
                let fileName = e.target.innerText;
                console.log({ command: 'openConfigTable', name: fileName, configPath: currentPath });
                vscode.postMessage({ command: 'openConfigTable', name: fileName, configPath: currentPath });
            }
        });
        // 文件名列表右键击事件
        topPane.addEventListener('contextmenu', function (e) {
            e.preventDefault();
            if (!e.target.classList.contains('file-item')) {
                fileOperateMenu.style.display = 'none';
                currentTarget = e.target;
                rightPaneMenu.style.display = 'block';
                rightPaneMenu.style.top = \`\${e.clientY}px\`;
                rightPaneMenu.style.left = \`\${e.clientX}px\`;
            }
        });
        // 点击页面其他地方隐藏自定义菜单
        document.addEventListener('click', () => {
            fileOperateMenu.style.display = 'none';
            rightPaneMenu.style.display = 'none';
        });

        // 自定义菜单选项点击事件
        document.getElementById('context-delete').addEventListener('click', () => {
            if (currentTarget) {
                fileOperateMenu.style.display = 'none';
            }
            vscode.postMessage({
                command: 'deleteConfig',
                configPath: currentPath,
                configName: currentConfigName
            });
        });
        function getHashCode(str) {
            let hash = 0;
            if (str.length === 0) return hash;
            for (let i = 0; i < str.length; i++) {
                const char = str.charCodeAt(i);
                hash = (hash << 5) - hash + char;
                hash |= 0; // 转换为32位整数
            }
            return hash;
        }
        changeButton.addEventListener('click', () => {
            if (showType === 'model') {
                // 切换到输出
                changeButton.textContent = '切换模板'
                const newModelStr = getModelStr();
                console.log('hash');
                console.log(getHashCode(newModelStr));
                console.log(getHashCode(modelStr));
                if (getHashCode(newModelStr) !== getHashCode(modelStr) || outputStr.length === 0) {
                    console.log('need refresh');
                    outputStr = formatStrings(newModelStr, getTableData());
                    modelStr = newModelStr;
                }
                console.log('refresh');
                updateCodeContent(outputStr);
                showType = 'output';
            } else {
                // 切换到模板
                changeButton.textContent = '切换输出'
                updateCodeContent(modelStr);
                showType = 'model';
            }
        });
        saveModel.addEventListener('click', () => {
            saveModelFunc();
        });
        document.getElementById('context-rename').addEventListener('click', async () => {
            if (currentTarget) {
                vscode.postMessage({ command: 'renameConfirmed', oldFileName: currentTarget.textContent });
                fileOperateMenu.style.display = 'none';
            }
        });
        document.getElementById('context-new-config').addEventListener('click', async () => {
            vscode.postMessage({ 
                command: 'newConfig',
                configPath: currentPath,
                configName: currentConfigName,
            });
        });
        function addFileItem(fileName) {
            const newFileItem = document.createElement('li');
            newFileItem.classList.add('file-item');
            newFileItem.textContent = fileName;
            fileList.appendChild(newFileItem);
        }
        function saveConfigToXlsx() {
            const configData = getTableData();
            vscode.postMessage({
                command: 'saveConfig',
                configData: configData,
                configPath: currentPath,
                configName: currentConfigName
            });
        }
        // 接收插件 ts 端的消息
        window.addEventListener('message', (event) => {
            const message = event.data;
            console.log(message);
            switch (message.command) {
                case 'renameConfirmed':
                    // 显示 XLSX 数据
                    const fileName = message.fileName;
                    const listItem_mv = Array.from(fileList.children).find(li => li.textContent === fileName);
                    if (listItem_mv) {
                        listItem_mv.remove();
                    }
                    break;
                case 'rename':
                    // 恢复文件名
                    const oldFileName = message.oldFileName;
                    const newFileName = message.fileName;
                    const listItem = Array.from(fileList.children).find(li => li.textContent === oldFileName);
                    if (listItem && newFileName) {
                        listItem.textContent = newFileName;
                    }
                    break;
                case 'tableRefresh':
                    const tableData = message.tableData;
                    console.log('Received table data:', tableData);
                    setTableRefresh(tableData);
                    outputStr = formatStrings(modelStr, getTableData());
                    break;
                case 'init':
                    currentPath = message.configPath;
                    console.log(message.configNameLists);
                    message.configNameLists.forEach(configName => {
                        addFileItem(configName);
                    });
                    break;
                case 'saveConfig':
                    saveConfigToXlsx()
                    break;
                case 'showModel':
                    modelStr = message.modelDataStr
                    console.log(modelStr)
                    updateCodeContent(modelStr)
                    break;
                case 'newConfigResp':
                    const newConfigName = message.newConfigName;
                    if (newConfigName) {
                        addFileItem(newConfigName);
                    }
                    break;
                case 'deleteConfigResp':
                    if (message.result) {
                        currentTarget.remove();
                    }
            }

        });
        window.addEventListener('message', (event) => {
            const message = event.data;
            if (message.command === 'displayXlsx') {
                const data = message.data;
                table.innerHTML = '';
                data.forEach((row) => {
                    const tr = document.createElement('tr');
                    row.forEach((cell) => {
                        const td = document.createElement('td');
                        td.contentEditable = true;
                        td.textContent = cell;
                        tr.appendChild(td);
                    });
                    table.appendChild(tr);
                });
            }
        });
        function setTableRefresh(data) {
            // 清空表格
            const tbody = table.querySelector('tbody') || table.createTBody();
            tbody.innerHTML = ''; // 清空当前表格内容
            // 动态填充表格内容
            data.forEach((rowData) => {
                const row = tbody.insertRow();
                rowData.forEach((cellData) => {
                const cell = row.insertCell();
                cell.textContent = cellData;
                cell.contentEditable = true;
                cell.addEventListener('input', checkAndAddRowsCols); // 绑定事件监听器
                });
            });
        }

        // 检查最后一行和最后一列，并动态增加
        function ensureEmptyRowsAndColumns(table) {
          const rows = table.rows.length;
          const cols = table.rows[0] ? table.rows[0].cells.length : 0;
        
          // 确保表格有至少一行一列
          if (rows < 1) {
            addRow(table);
          }
          if (cols < 1) {
            addColumn(table);
          }
        
          // 检查最后一行
          for (let i = rows - 1; i < rows; i++) {
            if (i >= 0 && !isRowEmpty(table.rows[i])) {
              addRow(table); // 如果最后一行有内容，则添加新行
              break;
            }
          }
        
          // 检查最后一列
          for (let j = cols - 1; j < cols; j++) {
            if (j >= 0 && !isColumnEmpty(table, j)) {
              addColumn(table); // 如果最后一列有内容，则添加新列
              break;
            }
          }
        }
        
        // 动态添加新行
        function addRow(table) {
          const newRow = table.insertRow();
          const cols = table.rows[0].cells.length;
          
          for (let i = 0; i < cols; i++) {
            const newCell = newRow.insertCell();
            newCell.contentEditable = true;
            newCell.addEventListener('input', checkAndAddRowsCols); // 绑定事件监听器
          }
        }
        
        // 动态添加新列
        function addColumn(table) {
          for (let i = 0; i < table.rows.length; i++) {
            const newCell = table.rows[i].insertCell();
            newCell.contentEditable = true;
            newCell.addEventListener('input', checkAndAddRowsCols); // 绑定事件监听器
          }
        }
        
        // 检查行是否为空
        function isRowEmpty(row) {
          return Array.from(row.cells).every(cell => !cell.textContent.trim());
        }
        
        // 检查列是否为空
        function isColumnEmpty(table, colIndex) {
          return Array.from(table.rows).every(row => !row.cells[colIndex].textContent.trim());
        }
        
        // 表格内容变动时的回调函数，检查并增加行列
        function checkAndAddRowsCols() {
            console.log(checkAndAddRowsCols);
          ensureEmptyRowsAndColumns(table);
        }
        function getTableData() {
            const rows = table.querySelectorAll('tr');
            return Array.from(rows).map((row) => {
                return Array.from(row.querySelectorAll('td')).map((cell) => cell.textContent);
            });
        }
        // 显示默认的多行多列的 XLSX 表数据
        document.addEventListener('DOMContentLoaded', () => {
            const defaultData = [[]];
            setTableRefresh(defaultData);
            vscode.postMessage({ command: 'ready' });
        });
    </script>
</body>

</html>`;
}

export function activate(context: vscode.ExtensionContext) {

    console.log('Congratulations, your extension "modelfilegenerator" is now active!');

    // 初始化 获取storagePath这个全局变量，解析这个路径下的文件目录结构
    let storagePath = context.globalState.get<string>('storagePath');
    
    let fileStructure: FileNode[] = [];
    if (storagePath) {
        fileStructure = readDirectory(storagePath);
    } else {
        storagePath = '';
    }

    vscode.window.registerWebviewViewProvider('myView', {
        resolveWebviewView(webviewView: vscode.WebviewView) {
            // 设置 Webview 的 HTML 内容
            webviewView.webview.options = {
                enableScripts: true
            };

            // HTML 内容：自定义的模板列表，并设置不同的字体大小
            webviewView.webview.html = getWebviewContent();

            async function handleRenameItem(message: any) {
                const newName = await vscode.window.showInputBox({
                    prompt: '请输入新的模板项名称',
                    value: message.oldName || '' // 使用旧名称作为默认值
                });

                if (newName !== undefined && newName !== message.oldName) {
                    // 将新的名称发送回 WebView
                    webviewView.webview.postMessage({
                        command: 'updateItemName',
                        itemId: message.itemId,
                        newName: newName
                    });
                }
            }
            async function handleRenameFolder(message: any) {
                const newName = await vscode.window.showInputBox({
                    prompt: '请输入新的文件夹名称',
                    value: message.oldName || '' // 使用旧名称作为默认值
                });

                if (newName !== undefined && newName !== message.oldName) {
                    // 将新的名称发送回 WebView
                    webviewView.webview.postMessage({
                        command: 'updateFolderName',
                        folderId: message.folderId,
                        newName: newName
                    });
                }
            }
            webviewView.webview.onDidReceiveMessage(
                async (message) => {
                    console.log('xml message');
                    switch (message.command) {
                        case 'showInputBox':
                            // 打开 VSCode 输入框
                            let inputName = await vscode.window.showInputBox({
                                prompt: `Enter ${message.type} Name`, // 根据点击的按钮提示是 folder 还是 item
                            });
                            let ret = true;
                            // 创建文件夹或者创建item
                            if (!inputName) {
                                break;
                            }
                            if (message.type !== 'folder') {
                                inputName = inputName + '-item';
                            }
                            ret = await createFolderOrItem(path.join(storagePath, inputName), message.type);
                            if (inputName) {
                                // 根据用户输入，发送消息回WebView
                                webviewView.webview.postMessage({
                                    command: message.type === 'folder' ? 'createFolder' : 'createItem',
                                    name: inputName,
                                    status: ret
                                });
                            }
                            break;
                        case 'openEditor':
                            const name = message.itemName;
                            const configPath = message.itemPath;
                            vscode.commands.executeCommand('modelfilegenerator.openNewEditor', configPath, name);
                            break;
                        case 'renameItem':
                            await handleRenameItem(message);
                            break;
                        case 'renameFolder':
                            await handleRenameFolder(message);
                            break;
                        case 'ready':
                            webviewView.webview.postMessage({
                                command: 'loadFileStructure',
                                data: fileStructure
                            });
                            break;
                    }
                },
                undefined,
                context.subscriptions
            );
        }
    });
    context.subscriptions.push(
        vscode.commands.registerCommand('modelfilegenerator.openNewEditor', (modelPath: string, name: string) => {
            const panel = vscode.window.createWebviewPanel(
                'editor',
                name,
                vscode.ViewColumn.One,
                {
                    enableScripts: true,
                }
            );

            panel.webview.onDidReceiveMessage(
                async (message) => {
                    console.log('Received message:', message);
                    switch (message.command) {
                        case 'renameConfirmed':
                            // 输入新的fileName
                            const reFileName = await vscode.window.showInputBox({
                                placeHolder: `${message.oldFileName}`,
                                prompt: `Enter new ${message.oldFileName} Name`,
                            });
                            panel.webview.postMessage({ command: 'rename', oldFileName: message.oldFileName, fileName: reFileName });
                            break;
                        case 'ready':
                            panel.webview.postMessage({
                                command: 'init',
                                configNameLists: readModelConfigList(modelPath),
                                configPath: modelPath,
                                modelConfig: []
                            });
                            const modelData = await getModelData(modelPath);
                            panel.webview.postMessage({
                                command: 'showModel',
                                modelDataStr: modelData
                            });
                            break;
                        case 'openConfigTable':
                            // vscode.postMessage({ command: 'openConfigTable', name: fileName })
                            const tableData = await readModelConfig(path.join(message.configPath, message.name + '.xlsx'));
                            panel.webview.postMessage({
                                command: 'tableRefresh',
                                tableData: tableData
                            });
                            break;
                        case 'saveConfig':
                            saveModelConfig(path.join(message.configPath, message.configName + '.xlsx'),
                                message.configData);
                            break;
                        case 'saveModel':
                            saveModelStr(path.join(message.configPath, 'model.xml'), message.modelStr);
                            break;
                        case 'newConfig':
                            // 输入新的fileName
                            const newConfigName = await vscode.window.showInputBox({
                                placeHolder: `New Config Name`,
                                prompt: `Enter new config file Name`,
                            });
                            if (newConfigName) {
                                saveEmptyXlsxFile(path.join(message.configPath, newConfigName + '.xlsx'));
                                panel.webview.postMessage({
                                    command: 'newConfigResp',
                                    newConfigName: newConfigName
                                });
                            }
                            break;
                        case 'deleteConfig':
                            const ret = await deleteFile(path.join(message.configPath, message.configName + '.xlsx'));
                            panel.webview.postMessage({
                                command: 'deleteConfigResp',
                                result: ret
                            });


                    }
                },
                undefined,
                context.subscriptions
            );
            panel.webview.html = getEditorContent(context, panel.webview);
            console.log('openNewEditor');
        })
    );
    // 选择设置存储地址，并持久化保存
    context.subscriptions.push(
        vscode.commands.registerCommand('modelfilegenerator.setStoragePath', async () => {
            const storagePath = await vscode.window.showOpenDialog({
                canSelectFiles: false,
                canSelectFolders: true,
                canSelectMany: false,
                openLabel: 'Select Folder',
            });
            if (storagePath && storagePath[0]) {
                const selectedPath = storagePath[0].fsPath;
                // 保存到状态管理器中
                context.globalState.update('storagePath', selectedPath);
                vscode.window.showInformationMessage(`Selected storage path: ${selectedPath}`);
            }

        })
    );
    // 保存config文件
    context.subscriptions.push(
        vscode.commands.registerCommand('modelfilegenerator.saveConfig', async () => {
        })
    );
}
// This method is called when your extension is deactivated
export function deactivate() { }
